//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.jeecg.p3.system.web;

import com.alibaba.fastjson.JSONObject;
import com.jeecg.p3.system.service.JwSystemProjectService;
import com.jeecg.p3.weixinInterface.entity.WeixinAccount;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.jeecgframework.p3.core.util.PropertiesUtil;
import org.jeecgframework.p3.core.util.SignatureUtil;
import org.jeecgframework.p3.core.util.oConvertUtils;
import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import weixin.util.redis.JedisPoolUtil;

@Controller
@RequestMapping({"/linksucai"})
public class LinksucaiController extends BaseController {
    private static final Logger logger = Logger.getLogger(LinksucaiController.class);
    @Autowired
    private JwSystemProjectService jwSystemProjectService;
    private static String SIGN_KEY = "";
    private static final String SCOPE = "snsapi_base";
    private static String domain = "";

    public LinksucaiController() {
    }

    public static void setDomain(String newdomain) {
        domain = newdomain;
    }

    public static String getDomain() {
        return domain;
    }

    @RequestMapping(
            value = {"link"},
            method = {RequestMethod.GET, RequestMethod.POST}
    )
    public void link(HttpServletRequest request, HttpServletResponse response) {
        long start = System.currentTimeMillis();
        logger.info("-------[LINKSTARTIME]--------------开始时间戳------------>" + start);

        try {
            String linkid = request.getParameter("linkid");
            String jwid = request.getParameter("jwid");
            String state = request.getParameter("state");
            WeixinAccount weixinAccount = JedisPoolUtil.getWxAccount(jwid);
            if (weixinAccount == null) {
                logger.error("------[异常]----------OpenWX----------微信原始ID参数异常,查询公众号失败，原始ID: ------" + jwid);
                return;
            }

            String code = request.getParameter("code");
            String APPID = weixinAccount.getAccountappid();
            String APPSECRET = weixinAccount.getAccountappsecret();
            String web_oauth_url;
            String weixinOauthURL;
            if (code != null && code.length() != 0) {
                logger.info("-------[LINKWXSTEP2_START]------------距离开始时间戳耗时-------------->" + (System.currentTimeMillis() - start));
                web_oauth_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
                web_oauth_url = web_oauth_url.replace("APPID", APPID);
                web_oauth_url = web_oauth_url.replace("SECRET", APPSECRET);
                web_oauth_url = web_oauth_url.replace("CODE", code);
                logger.info("------------------code-----------------" + code);
                logger.info("-------[LINKWXSTEP2_REQUEST]调用微信oauth2接口获取openid请求-------------------------->" + (System.currentTimeMillis() - start) + "ms");
                JSONObject json2 = this.httpRequest(web_oauth_url, "POST", (String)null);
                logger.info("-------[LINKWXSTEP2_RESPONSE]调用微信oauth2接口获取openid响应-------------------------->" + (System.currentTimeMillis() - start) + "ms");
                weixinOauthURL = (String)json2.get("openid");
                logger.info("----------------get--openid-----------------" + weixinOauthURL);
                String jeewxUrl = domain + "/" + this.jwSystemProjectService.queryById(linkid).getHdzsUrl();
                if (oConvertUtils.isEmpty(jeewxUrl)) {
                    logger.error("------[异常]----------OpenWX----------链接素材ID参数异常,查询数据失败，Link ID: ------" + linkid);
                    return;
                }

                logger.info("----------------outerLink------1-----------" + jeewxUrl);
                String queryParam;
                if (oConvertUtils.isNotEmpty(jeewxUrl)) {
                    jeewxUrl = jeewxUrl.replace("${openid}", weixinOauthURL);
                    jeewxUrl = jeewxUrl.replace("${wxid}", weixinAccount.getWeixinAccountid());
                    jeewxUrl = jeewxUrl.replace("${wxcode}", weixinAccount.getAccountnumber());
                    jeewxUrl = jeewxUrl.replace("${appid}", weixinAccount.getAccountappid());
                    jeewxUrl = jeewxUrl.replace("${appsecret}", weixinAccount.getAccountappsecret());
                    jeewxUrl = jeewxUrl.replace("${accesstoken}", weixinAccount.getAccountaccesstoken());
                    queryParam = oConvertUtils.getString(json2.get("access_token"));
                    jeewxUrl = jeewxUrl.replace("${utoken}", queryParam);
                }

                logger.info("----------------request.getQueryString()-------2----------" + request.getQueryString());
                queryParam = request.getQueryString();
                if (oConvertUtils.isNotEmpty(queryParam)) {
                    jeewxUrl = jeewxUrl + "&" + queryParam;
                }

                logger.info("----------------outerLink-------3----------" + jeewxUrl);
                String sign = SignatureUtil.sign(this.getSignMap(jeewxUrl), SIGN_KEY);
                logger.info("-------[LINKWXSTEP2_END]--------------距离开始时间戳耗时------------>" + (System.currentTimeMillis() - start) + "ms");
                response.sendRedirect(jeewxUrl + "&sign=" + sign);
            } else {
                logger.info("-------[LINKWXSTEP1_START]-----------距离开始时间戳耗时--------------->" + (System.currentTimeMillis() - start) + "ms");
                web_oauth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
                String REDIRECT_URI = request.getRequestURI();
                if (REDIRECT_URI.indexOf(domain) == -1) {
                    REDIRECT_URI = domain.replace(request.getContextPath(), "") + REDIRECT_URI;
                }

                logger.info("------------------REDIRECT_URI--------1---------" + REDIRECT_URI);
                REDIRECT_URI = REDIRECT_URI + "?" + request.getQueryString();
                logger.info("------------------REDIRECT_URI--------2---------" + REDIRECT_URI);
                REDIRECT_URI = URLEncoder.encode(REDIRECT_URI, "UTF-8");
                weixinOauthURL = web_oauth_url.replace("APPID", APPID).replace("REDIRECT_URI", REDIRECT_URI).replace("SCOPE", "snsapi_base");
//                weixinOauthURL = web_oauth_url.replace("APPID", APPID).replace("REDIRECT_URI", REDIRECT_URI).replace("SCOPE", "snsapi_userinfo");
                if (oConvertUtils.isNotEmpty(state)) {
                    weixinOauthURL = weixinOauthURL.replace("STATE", state);
                }

                logger.info("------------------weixinOauthURL-----------------" + weixinOauthURL);
                logger.info("-------[LINKWXSTEP1_END]--------------距离开始时间戳耗时------------>" + (System.currentTimeMillis() - start) + "ms");
                response.sendRedirect(weixinOauthURL);
            }
        } catch (Exception var18) {
            ;
        }

    }

    private JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpUrlConn = null;

        try {
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection)url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setConnectTimeout(4500);
            httpUrlConn.setReadTimeout(4500);
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

            OutputStream outputStream;
            if (null != outputStr) {
                outputStream = httpUrlConn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;

            while((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException var22) {
            ;
        } catch (Exception var23) {
            ;
        } finally {
            try {
                httpUrlConn.disconnect();
            } catch (Exception var21) {
                var21.printStackTrace();
            }

        }

        return jsonObject;
    }

    private Map<String, String> getSignMap(String url) {
        Map<String, String> paramMap = new HashMap();
        url = url.substring(url.indexOf("?") + 1);
        String[] params = url.split("&");

        for(int i = 0; i < params.length; ++i) {
            String param = params[i];
            if (param.indexOf("=") != -1) {
                String[] values = param.split("=");
                if (values != null && values.length == 2) {
                    if ("nickname".equals(values[0])) {
                        paramMap.put(values[0], URLDecoder.decode(values[1]));
                    } else {
                        paramMap.put(values[0], values[1]);
                    }
                }
            }
        }

        return paramMap;
    }

    static {
        PropertiesUtil oAuth = new PropertiesUtil("p3-web-sysconfig.properties");
        SIGN_KEY = oAuth.readProperty("oAuthSignKey");
        domain = oAuth.readProperty("oAuthDomain");
    }
}
